import React, { Component } from 'react';
import './index.scss';
import NavHeader from '../../components/NavHeader';
import HouseItem from '../../components/HouseItem'
import { API } from '../../utils/axios';
import { Link } from 'react-router-dom'
import { Toast } from 'antd-mobile';

const BMap = window.BMap;
// 覆盖物样式
const labelStyle = {
  cursor: "pointer",
  border: "0px solid rgba(255, 0, 0)",
  padding: "0px",
  whiteSpace: "nowrap",
  fontSize: "12px",
  color: "rgb(255, 255, 255)",
  textAlign: "center"
}

export default class Map extends Component {

  state = {
    housesList: [],
    isShowList: false
  }

  componentDidMount() {
    this.initMap();
  }

  render() {
    return (
      <div className="map">
        <NavHeader>地图找房</NavHeader>
        <div id="container"></div>
        {/* 渲染房屋列表 */}
        {this.renderHousesList()}
      </div>
    )
  }

  initMap() {
    /**
     * 初始化地图
     * 1.拿到本地城市
     * 2.需要使用window来访问全局对象,已经在头部简化
     * 3.使用百度地图解析器
     * 4.设置中心点,初始化地图
     *  =>1.缩放控件
     *  =>2.添加比例尺
     */
    const { label, value } = JSON.parse(window.localStorage.getItem('hkzf_city'));

    var map = new BMap.Map("container");
    this.map = map;

    let myGeo = new BMap.Geocoder();

    myGeo.getPoint(label || "广东省潮州市饶平县", (point) => {
      if (point) {
        map.centerAndZoom(point, 11);

        map.addControl(new BMap.NavigationControl());
        map.addControl(new BMap.ScaleControl());

        // 创建文本覆盖物
        this.renderOverlays(value);
      }
    }, label || "潮州市");

    // 地图移动时隐藏房源列表
    map.addEventListener('movestart', () => {
      if (!this.state.isShowList) return;
      this.setState({ isShowList: false })
    });
  }

  // 渲染文本覆盖物
  async renderOverlays(id) {
    try {
      // 开启加载提示
      Toast.loading('加载中...', 0, null, false);
      const { data } = await API.get(`/area/map?id=${id}`);
      // 关闭提示
      Toast.hide();

      // 获取下一个缩放级别，类型
      const { nextZoom, type } = this.getTypeAndZoom();

      data.body.forEach(item => {
        this.createOverlays(item, nextZoom, type);
      });
    } catch (error) {
      // 关闭提示
      Toast.hide();
    }
  }

  // 计算覆盖物的类型和下一个级别
  getTypeAndZoom() {
    // 获取当前缩放级别,百度api方法
    const zoom = this.map.getZoom();
    // 下一个缩放级别，和覆盖物类型
    let nextZoom, type;
    if (zoom >= 10 && zoom < 12) {
      // 区
      nextZoom = 13;
      type = 'circle';
    } else if (zoom >= 12 && zoom < 14) {
      // 镇
      nextZoom = 15;
      type = 'circle';
    } else if (zoom >= 14 && zoom < 16) {
      type = 'rect';
    }
    return { nextZoom, type };
  }

  // 创建覆盖物
  createOverlays(data, zoom, type) {
    // 二级解构赋值
    const {
      coord: { longitude, latitude },
      label: areaName, // 取别名
      count,
      value: id
    } = data;

    const areaPoint = new BMap.Point(longitude, latitude);

    type === 'circle' ? this.createCircle({ areaPoint, areaName, count, id, zoom }) : this.createRect({ areaPoint, areaName, count, id });
  }

  // 创建区，镇级覆盖物
  createCircle({ areaPoint, areaName, count, id, zoom }) {
    var label = new BMap.Label(' ', {
      position: areaPoint, // 指定文本标注所在的地理位置
      offset: new BMap.Size(-35, -35)
    });

    label.setContent(`
        <div class="bubble">
          <p class="name">${areaName}</p>
          <p >${count}套</p>
        </div>
      `);

    label.setStyle(labelStyle);

    label.addEventListener('click', () => {
      /**
       * 进入下一级
       * 1.以当前点击的覆盖物为中心放大地图
       * 2.清除当前覆盖物信息
       * 3.重新调用
       */
      this.map.centerAndZoom(areaPoint, zoom);

      setTimeout(() => { // 防止报错
        this.map.clearOverlays();
      }, 10);

      this.renderOverlays(id);
    });
    this.map.addOverlay(label);
  }

  // 创建小区覆盖物
  createRect({ areaPoint, areaName, count, id }) {
    var label = new BMap.Label(' ', {
      position: areaPoint, // 指定文本标注所在的地理位置
      offset: new BMap.Size(-50, -28)
    });

    label.setContent(`
        <div class="rect">
          <span class="housename">${areaName}</span>
          <span class="housenum">${count}套</span>
          <i class="arrow"></i>
        </div>
      `);

    label.setStyle(labelStyle);

    label.addEventListener('click', e => {
      this.getHousesList(id);
      /**
       * 地图移动到中间 panBy() 方法
       * 公式：
       *    垂直：(window.innerHeight - 330) / 2 - target.clientY
       *    水平：window.innerWidth / 2 -target.clientX
       */
      const target = e.changedTouches[0];
      // console.log(target);
      this.map.panBy(window.innerWidth / 2 - target.clientX, (window.innerHeight - 330) / 2 - target.clientY);
    });
    this.map.addOverlay(label);
  }

  // 获取小区房源数据
  async getHousesList(id) {
    try {
      // 开启加载提示
      Toast.loading('加载中...', 0, null, false);
      const { data } = await API.get(`/houses?id=${id}`);
      // 关闭
      Toast.hide();
      this.setState({
        housesList: data.body.list,
        isShowList: true
      });
    } catch (error) {
      // 关闭
      Toast.hide();
    }
  }

  // 渲染房源列表
  renderHousesList() {
    return (
      <div className={"house-list " + (this.state.isShowList ? 'show' : '')}>
        <div className="title-wrap">
          <h1 className="list-title">房屋列表</h1>
          <Link className="title-more" to="/home/list">
            更多房源
          </Link>
        </div>
        {/* 房屋信息结构 */}
        <HouseItem housesList={this.state.housesList} />
      </div>
    )
  }
}
